<!--
 * @Author: WuFeng <763467339@qq.com>
 * @Date: 2024-06-17 12:41:14
 * @LastEditTime: 2024-06-17 15:00:40
 * @LastEditors: WuFeng <763467339@qq.com>
 * @Description: 
 * @FilePath: \chu-meng\client\src\pages\Design\components\SidebarArea\DataSidebar\CreateDrawer.vue
 * Copyright 版权声明
-->
<template>
  <a-drawer :title="titleMap[handleType]" :size="`large`" :open="open" @close="onClose">
    <template #extra>
      <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
      <a-button style="margin-right: 8px" @click="onResetForm">重置</a-button>
      <a-button type="primary" @click="onSubmit">提交</a-button>
    </template>
    <a-form
      ref="formRef"
      name="custom-validation"
      size="small"
      :model="formData"
      :rules="rules"
      v-bind="{
        labelCol: { span: 5 },
        // wrapperCol: { span: 14 },
      }"
      @finish="handleFinish"
      @validate="handleValidate"
      @finishFailed="handleFinishFailed"
    >
    <a-form-item has-feedback label="数据源名称" name="name">
      <a-input v-model:value="formData.name" placeholder="请输入数据源名称" allowClear />
    </a-form-item>
    <a-form-item has-feedback label="数据源描述" name="desc">
      <a-textarea :auto-size="{ minRows: 2, maxRows: 3 }" placeholder="请输入数据源数据源描述" v-model:value="formData.desc" />
    </a-form-item>
    <a-form-item has-feedback label="请求地址" name="url">
      <a-input v-model:value="formData.url" placeholder="请输入请求地址" allowClear />
    </a-form-item>
    <a-form-item label="请求方法" name="type">
      <a-select v-model:value="formData.type" placeholder="请选择请求方法" allowClear>
        <a-select-option value="GET">GET</a-select-option>
        <a-select-option value="POST">POST</a-select-option>
        <a-select-option value="OPTIONS">OPTIONS</a-select-option>
        <a-select-option value="PUT">PUT</a-select-option>
        <a-select-option value="PATCH">PATCH</a-select-option>
        <a-select-option value="DELETE">DELETE</a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item has-feedback label="超时时长（毫秒）" name="timeout">
      <a-input-number style="width: 100%;" v-model:value="formData.timeout" :min="1000" placeholder="请输入超时时长（毫秒）" allowClear />
    </a-form-item>
    <a-form-item has-feedback label="请求头信息" name="headers">
      <ul class="headersUL">
        <li v-for="(item, index) in formData.headers" :key="index">
          <a-space style="width: 100%;">
            <a-input v-model:value="item.key" placeholder="key" allowClear style="width: 120px;" />
            <span style="width: 15px;">：</span>
            <a-input v-model:value="item.value" placeholder="value" allowClear style="flex: 1;"/>
            <a-select v-model:value="item.type" placeholder="信息类型" style="width: 100px;">
              <a-select-option value="string">字符串</a-select-option>
              <a-select-option value="boolean">布尔</a-select-option>
              <a-select-option value="expression">表达式</a-select-option>
            </a-select>
            <DeleteOutlined key="delete" title="删除" @click="handleDeleteHeaders(index)" />
          </a-space>
        </li>
      </ul>
      <a-button type="primary" size="small" @click="handleAddHeaders">
        <template #icon>
          <PlusOutlined />
        </template>
        添加
      </a-button>
    </a-form-item>
    <a-form-item has-feedback label="添加数据处理函数">
      <a-select v-model:value="formData.processFunctionType" @change="onChangeProcessFunctionType" placeholder="选择添加" allowClear style="width: 250px;">
        <a-select-option v-for="(item, index) in formData.processFunctionTypeOptions" :key="index" :value="item.value">
          {{ item.label }}
        </a-select-option>
      </a-select>
      <div class="processFunWrap">
        <div class="processFunWrap_item" v-for="(item, index) in formData.processFunctionTypeList" :key="index">
          <h3>{{ item.label }}</h3>
          <p>
            <a-space>
              <a-textarea :auto-size="{ minRows: 5, maxRows: 8 }" placeholder="请输入数据源数据源描述" v-model:value="item.code" :show-count="false" />
              <DeleteOutlined key="delete" title="删除" @click="handleDeleteProcessFun(index)" />
            </a-space>
          </p>
        </div>
      </div>
    </a-form-item>
  </a-form>
  </a-drawer>
</template>

<script setup name="CreateDrawer">
import { ref, defineExpose, toRaw } from 'vue'
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue'

const open = ref(false)
const titleMap = {
  'create': '新建数据源',
  'update': '编辑数据源'
}
const handleType = ref('create')

const formRef = ref(null)
const rules = {
  name: [{ required: true, message: '请输入数据源名称', trigger: 'change' }],
  desc: [{ required: true, message: '请输入数据源数据源描述', trigger: 'change' }],
  url: [{ required: true, message: '请输入请求地址法', trigger: 'change' }],
  type: [{ required: true, message: '请选择请求方法', trigger: 'change' }]
}
const formData = ref({
})

// 删除数据处理函数
const handleDeleteProcessFun = (index) => {
  formData.value.processFunctionTypeList.splice(index, 1)
}

// 添加数据处理函数
const onChangeProcessFunctionType = (val) => {
  console.log(`🚀 ~ onChangeProcessFunctionType ~ val:`, val)
  // formData.value.processFunctionType = undefined
  let label = ''
  switch (val) {
    case 'isStart':
      label = '是否发起请求的计算函数'
      break
    case 'before':
      label = '请求前对参数的处理函数'
      break
    case 'success':
      label = '请求成功对结果的处理函数'
      break
    case 'fail':
      label = '请求失败对异常的处理函数'
      break
  }
  formData.value.processFunctionTypeList.push({
    value: val,
    label,
    code: ''
  })
}

// 添加请求头信息
const handleAddHeaders = () => {
  formData.value.headers.push({
    type: 'string',
    key: '',
    value: ''
  })
}

// 删除请求头信息
const handleDeleteHeaders = (index) => {
  formData.value.headers.splice(index, 1)
}

const onShow = ({ type = 'create', row = {} }) => {
  formData.value = {
    name: '',
    desc: '',
    url: '',
    type: 'GET',
    timeout: 5000,
    headers: [
      // {
      //   type: 'string',
      //   key: '',
      //   value: ''
      // }
    ],
    processFunctionTypeOptions: [
      {
        label: '是否发起请求的计算函数',
        value: 'isStart'
      },
      {
        label: '请求前对参数的处理函数',
        value: 'before'
      },
      {
        label: '请求成功对结果的处理函数',
        value: 'success'
      },
      {
        label: '请求失败对异常的处理函数',
        value: 'fail'
      }
    ],
    processFunctionType: undefined,
    processFunctionTypeList: []
  }
  handleType.value = type
  if (type === 'update') {
    formData.value = JSON.parse(JSON.stringify(row))
  }
  open.value = true
  formRef.value.resetFields()
}

const onClose = () => {
  open.value = false
}

const onSubmit = () => {
  formRef.value
    .validate()
    .then(() => {
      console.log('values', formData, toRaw(formData))
    })
    .catch(error => {
      console.log('error', error)
    })
}

const onResetForm = () => {
  formRef.value.resetFields()
}

defineExpose({
  onShow
})
</script>

<style lang="scss" scoped>
.headersUL{
  margin: 0;
  padding: 0;
}
.headersUL li{
  margin: 0;
  padding: 0;
  list-style: none;
  margin-bottom: 8px;
  :deep(.ant-space){
    .ant-space-item:nth-child(3) {
      flex: 1;
    }
  }
}
.processFunWrap{
  &_item{
    h3{
      font-weight: bold;
      margin: 8px 0;
      font-size: 12px;
    }
    p{
      :deep(.ant-space){
        width: 100%;
        .ant-space-item:nth-child(1) {
          flex: 1;
        }
      }
    }
  }
}
</style>

